<template>
  <el-dialog :title="`属性分组[${dataForm.attrgroupName}]-关联维护`" width="50%" draggable :close-on-click-modal="false" v-model="visible">
    <div style="margin-bottom: 20px">
      <el-popover :visible="relation.visible" placement="right" width="400" trigger="click">
        <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit(dataFormRef)"
          label-width="80px">
          <el-form-item label="属性名称" prop="attrId">
            <el-select v-model="dataForm.attrId" filterable placeholder="请选择">
              <el-option v-for="item in relation.dataList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="属性排序" prop="attrSort">
            <el-input-number v-model="dataForm.attrSort" :min="1" :max="10000" label="属性排序"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button @click="relation.visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit(dataFormRef)" :disabled="relation.submitted">确定</el-button>
          </el-form-item>
        </el-form>
        <template #reference>
          <el-button v-if="admin.isAuth('product:attrgroup:relation:save')" type="primary" @click="addRelationEvent()">
            新增关联
          </el-button>
        </template>
      </el-popover>
    </div>
    <el-table :data="table.dataList" border v-loading.lock="table.loading" element-loading-text="拼命加载中"
      style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="name" label="属性名" />
      <el-table-column prop="options" header-align="center" align="left" label="可选值列表" width="220">
        <template #default="scope">
          <span v-for="(i, index) in scope.row.options.split(';')" :key="index">
            <el-tag>{{ i }}</el-tag>&nbsp;
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="visible" header-align="center" align="center" label="快速展示" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.visible === 0" size="small" type="danger">否</el-tag>
          <el-tag v-else size="small">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="enable" header-align="center" align="center" label="启用状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.enable === 0" size="small" type="danger">禁用</el-tag>
          <el-tag v-else size="small">启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="100" label="操作">
        <template #default="scope">
          <el-button v-if="admin.isAuth('product:attrgroup:relation:delete')" size="small"
            @click="deleteRelationEvent(scope.row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import admin from "@/utils/admin";
import http from "@/utils/httpRequest";
import validate from "@/utils/validate";
import { ref, reactive, nextTick, defineExpose, defineEmits } from "vue";
import { ElMessageBox, FormInstance } from "element-plus";

// 弹窗是否显示
const visible = ref(false);

// 表单数据
const dataForm = reactive({
  attrId: [],
  attrSort: undefined,
  categoryId: undefined,
  attrgroupId: undefined,
  attrgroupName: undefined,
});

// 分组下的属性列表
const table = reactive({
  // 表格数据
  dataList: [],
  // 表格加载状态
  loading: false,
});

// 关联操作
const relation = reactive({
  // 级联数据
  dataList: [],
  // 是否显示
  visible: false,
  // 提交按钮是否禁用
  submitted: false,
});

// 表单校验规则
const dataRule = ref({
  attrId: validate.required("属性名称"),
  attrSort: validate.required("属性排序"),
});

// 表单引用
const dataFormRef = ref<FormInstance>();

// 品牌-分类数据列表初始化
const initPage = async (node) => {
  dataForm.categoryId = node.categoryId;
  dataForm.attrgroupId = node.attrgroupId;
  dataForm.attrgroupName = node.attrgroupName;
  visible.value = true;
  await nextTick();
  loadRelationData();
};

// 加载表格数据
const loadRelationData = () => {
  table.loading = true;
  http
    .post({
      url: `/product/attrgroup/relation/list?attrgroupId=${dataForm.attrgroupId}`,
    }).then(({ data }) => {
      table.dataList = http.success(data) ? data.body : [];
      table.loading = false;
    });
};

// 新增关联数据事件
const addRelationEvent = () => {
  dataForm.attrId = undefined;
  relation.visible = true;
  loadNotRelationData();
};

// 加载分组下没有关联的列表
const loadNotRelationData = () => {
  http
    .post({
      url: `/product/attrgroup/notrelation/list?categoryId=${dataForm.categoryId}`,
    })
    .then(({ data }) => {
      if (http.success(data)) {
        relation.dataList = data.body;
      }
    });
};

// 表单提交
const dataFormSubmit = (form: FormInstance | undefined) => {
  if (relation.submitted) {
    return;
  }
  form.validate((valid) => {
    if (valid) {
      relation.submitted = true;
      http
        .post({
          url: `/product/attrgroup/relation/save`,
          data: {
            attrId: dataForm.attrId,
            attrSort: dataForm.attrSort,
            attrgroupId: dataForm.attrgroupId,
          },
        })
        .then(({ data }) => {
          if (http.success(data, true, true)) {
            relation.visible = false;
            loadRelationData();
          }
          relation.submitted = false;
        });
    }
  });
};

// 删除关联关系
const deleteRelationEvent = (node) => {
  ElMessageBox.confirm(`确定要删除属性[${node.name}]的关联关系吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    http
      .post({
        url: `/product/attrgroup/relation/delete`,
        data: {
          attrId: node.id,
          attrgroupId: dataForm.attrgroupId,
        },
      })
      .then(({ data }) => {
        if (http.success(data, true, true)) {
          loadRelationData();
        }
      });
  });
};

// 暴露方法
defineExpose({ initPage });
</script>
